import axios from "axios"

class Request {
    static instance = new Request()

    constructor() {
        if (Request.instance) {
            return Request.instance
        }
        Request.instance = this

        axios.interceptors.request.use(
            (config) => {
                // config.headers.token = localStorage.getItem("token") || ''
                config.headers.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJpYXQiOjE3NTUzMTU4Nzd9.47ZOzCZskK2VgG3w54BPtrCgyLLNR-uqRo3k8L8-4KQ'
                return config
            },
            (err) => {
                return Promise.reject(err)
            }
        )

        axios.interceptors.response.use(
            (res) => {
                return res.data
            },
            (err) => {
                return Promise.reject(err)
            }
        )
    }

    static create(url) {
        axios.defaults.baseURL = url
    }

    static getInstance(url) {
        Request.create(url)
        return Request.instance
    }

    async request(url = '', method = 'get', data = {}, headers = {}) {

        if (['get', 'delete', 'head', 'options'].includes(method)) {
            return axios.request({
                url: encodeURI(url),
                method,
                params: data,
                headers
            })
        }
        return axios.request({
            url: encodeURI(url),
            method,
            data,
            headers
        })
    }
}

export const requestIns = Request.getInstance('/ftyyptapi')